package com.neuedu.service.impl;

import com.neuedu.entity.Address;
import com.neuedu.entity.User;
import com.neuedu.mapper.AddressMapper;
import com.neuedu.service.AddressService;
import com.neuedu.service.UserService;
import com.neuedu.vo.AddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private UserService userService;

    /**
     * 实现多表查询
     * 可以根据address对象中的id可以查到所有addressVo对象中信息，重点是可以查到这些地址是谁的
     * @return
     */
    @Override
    public List<AddressVo> getAll() {
        List<AddressVo> voList = new ArrayList<>();
        List<Address> list = addressMapper.selectAll();
        for (Address address : list){
            AddressVo addressVo = getById(address.getId());
            voList.add(addressVo);
        }
        return voList;
    }

    /**
     * 通过id可以查询到指定的addressVo中的所有信息
     * @param id
     * @return
     */
    @Override
    public AddressVo getById(Integer id) {
        AddressVo addressVo = new AddressVo();
        Address address = addressMapper.selectByPrimaryKey(id);
        User user = userService.findById(address.getUserId());
        addressVo.setId(address.getId());
        addressVo.setUserId(address.getUserId());
        addressVo.setAddr(address.getAddr());
        addressVo.setUsername(user.getUsername());
        return addressVo;
    }

    @Override
    public void insert(Address address) {
        addressMapper.insert(address);
    }

    @Override
    public void update(Address address) {
        addressMapper.updateByPrimaryKey(address);
    }

    @Override
    public void delete(Integer id) {
        addressMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByUserId(List<Integer> userIds) {
        Example example = new Example(Address.class);
        example.createCriteria().andIn("userId",userIds);
        addressMapper.deleteByExample(example);
    }

    /*@Override
    public void bathDelete(List<Integer> ids) {
        Example example = new Example(Address.class);
        example.createCriteria().andIn("id",ids);
        addressMapper.deleteByExample(example);
    }*/
}
